#include "switchstaus.h"
#include "ui_switchstaus.h"
#include <QMessageBox>

#include <QThread>
#include <QTimer>


//SwitchStaus::SwitchStaus(QWidget *parent)
SwitchStaus::SwitchStaus(const QString &Name,QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::SwitchStaus)
{

    ui->setupUi(this);

    setWindowFlags(Qt::FramelessWindowHint | Qt::Dialog);
    // setAttribute(Qt::WA_TranslucentBackground);
    // 自定义标题栏按钮连接
    connect(ui->btn_close, &QPushButton::clicked, this, &SwitchStaus::close);

    // 设置初始状态
    ui->ptn_ready->setStyleSheet("background-color: gray; border: 2px solid gray;outline: none; border-radius: 25px;width: 50px; height: 50px;");
    ui->ptn_halt->setStyleSheet("background-color: transparent; border: 2px solid yellow; border-radius: 25px; width: 48px; height: 48px;");
    ui->ptn_command->setStyleSheet("background-color: transparent; border: 2px solid green; border-radius: 25px;width: 48px; height: 48px;");
    ui->ptn_error->setStyleSheet("background-color: transparent; border: 2px solid red; border-radius: 25px; width: 48px; height: 48px;");

    // 默认左侧按钮显示为 halt
    ui->ptn_switch->setText("halt");

    // 连接按钮点击信号
    connect(ui->ptn_switch, &QPushButton::clicked, this, &SwitchStaus::handleLeftButtonClick);
    connect(ui->ptn_off, &QPushButton::clicked, this, &SwitchStaus::handleRightButtonClick);
    emit colorChanged("gray");    // 灰色
    mSwitchFlag = 0;
    // CNP_DOMAIN_ID domain = 0;
    mDeviceName = "ORS_"+Name.toStdString();
    flagInitCount=0;
    // //mDeviceName = "ORS_Cask";
    // //std::string serverAppID = std::toStdString(Name);
    // switchPublish = new CNPClient(domain, mDeviceName);

    // subEvent();
    // QTimer::singleShot(500, []() {
    //     QString pubcontent = "switchState(s=Ready)";
    //     pubMsg(pubcontent);
    // });

}

SwitchStaus::~SwitchStaus()
{
    std::cout<<"SwitchStaus析构函数"<<std::endl;
    //pubSwitchStatu("Ready");
    delete ui;
    //delete switchPublish; // 释放内存
}

// 左侧按钮点击槽函数
void SwitchStaus::handleLeftButtonClick()
{
    if (ui->ptn_switch->text() == "halt") {
        // 第一次点击，按钮改为 command，ptn_halt 设置为黄色，ptn_ready 恢复
        // ui->ptn_switch->setText("command");

        // ui->ptn_ready->setStyleSheet("background-color: transparent; border: 2px solid gray;outline: none; border-radius: 25px;width: 50px; height: 50px;");
        // ui->ptn_halt->setStyleSheet("background-color: yellow; border: 2px solid yellow; border-radius: 25px; width: 48px; height: 48px;");
        // ui->ptn_command->setStyleSheet("background-color: transparent; border: 2px solid green; border-radius: 25px;width: 48px; height: 48px;");
        // ui->ptn_error->setStyleSheet("background-color: transparent; border: 2px solid red; border-radius: 25px; width: 48px; height: 48px;");

        executeHaltLogic();  // 执行 halt 逻辑
    }
    else if (ui->ptn_switch->text() == "command") {
        // 第二次点击，按钮文本清空，ptn_command 设置为绿色，ptn_halt 恢复
        // ui->ptn_switch->setText("");
        // ui->ptn_ready->setStyleSheet("background-color: transparent; border: 2px solid gray;outline: none; border-radius: 25px;width: 50px; height: 50px;");
        // ui->ptn_halt->setStyleSheet("background-color: transparent; border: 2px solid yellow; border-radius: 25px; width: 48px; height: 48px;");
        // ui->ptn_command->setStyleSheet("background-color: green; border: 2px solid green; border-radius: 25px;width: 48px; height: 48px;");
        // ui->ptn_error->setStyleSheet("background-color: transparent; border: 2px solid red; border-radius: 25px; width: 48px; height: 48px;");
        executeCommandLogic();  // 执行 command 逻辑
    }
}

// 右侧按钮点击槽函数
void SwitchStaus::handleRightButtonClick()
{
    // 右侧按钮设置为 off，左侧按钮恢复为 halt 并设置为 ready
    // ui->ptn_switch->setText("halt");

    // // 恢复 pt_ready 状态为默认灰色背景
    // ui->ptn_ready->setStyleSheet("background-color: gray; border: 2px solid gray; outline: none; border-radius: 25px; width: 50px; height: 50px;");

    // // 恢复 pt_halt 状态为透明背景，边框为黄色
    // ui->ptn_halt->setStyleSheet("background-color: transparent; border: 2px solid yellow; border-radius: 25px; width: 48px; height: 48px;");

    // // 恢复 pt_command 状态为透明背景，边框为绿色
    // ui->ptn_command->setStyleSheet("background-color: transparent; border: 2px solid green; border-radius: 25px; width: 48px; height: 48px;");

    // // 恢复 pt_error 状态为透明背景，边框为红色
    // ui->ptn_error->setStyleSheet("background-color: transparent; border: 2px solid red; border-radius: 25px; width: 48px; height: 48px;");

    // 执行 "off" 逻辑
    executeOffLogic();
}

// 执行 off 逻辑
void SwitchStaus::executeOffLogic()
{
    // 显示 "off" 状态的相关逻辑
    QMessageBox::information(this, "状态", "执行 off 状态逻辑");
    // 这里你可以添加更多的 "off" 逻辑代码
    //emit colorChanged("gray");    // 灰色
    //pubSwitchStatu("Ready");
    QString pubcontent = "switchState(s=Ready)";
    pubMsg(pubcontent);
}


// 执行 halt 逻辑
void SwitchStaus::executeHaltLogic()
{
    QMessageBox::information(this, "状态", "执行 halt 状态逻辑");
    //emit colorChanged("yellow"); // 黄色，作为例子
    //pubSwitchStatu("Enable");
    QString pubcontent = "switchState(s=Enable)";
    pubMsg(pubcontent);
}

// 执行 command 逻辑
void SwitchStaus::executeCommandLogic()
{
    QMessageBox::information(this, "状态", "执行 command 状态逻辑");
    //emit colorChanged("green");  // 绿色
    //pubSwitchStatu("Command");
    QString pubcontent = "switchState(s=Command)";
    pubMsg(pubcontent);
}

void SwitchStaus::pubSwitchStatu(QString switchStatu)
{
    std::cout<<"mDeviceName = "<<mDeviceName<<std::endl;
    msgSwitchStatu.device_id(mDeviceName);

    auto now = std::chrono::system_clock::now();
    auto timestamp_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
                            now.time_since_epoch()
                            ).count();
    msgSwitchStatu.device_id(std::to_string(timestamp_ms));

    QString pubcontent = "switchState(s="+switchStatu+")";
    msgSwitchStatu.content(pubcontent.toStdString());
    if (!switchPublish)
        std::cout << "switchPublish is dead" << std::endl;
    else
    {
        CNP_RESULT result = switchPublish->publishCmdRequest(msgSwitchStatu);
        if (result == CNP_RESULT::CNP_PUBLISH_SUCCESS) {
            std::cout << "Message " << msgSwitchStatu.content() << " published successfully." << std::endl;
        }
        else {
            std::cout << "Failed to publish message " << "." << std::endl;
        }
    }
}

// void SwitchStaus::subEvent()
// {
//     if (!switchPublish) {
//         qWarning() << "SwitchStatus subStatuScriber not initialized";
//         //return CNP_RESULT::CNP_ERROR;
//     }

//     // 使用 lambda 将 subscribeCallback 转为成员函数调用
//     auto callback = [this](const CnpMsg &msg) {
//         this->eventStatuCallback(msg);
//     };

//     // 这里直接传入 lambda，假设 subscribeCmdRequest 接收 std::function
//     CNP_RESULT result = switchPublish->subscribeEvent(callback);

//     if (result == CNP_RESULT::CNP_SUBSCRIBE_SUCCESS)
//     {
//         qDebug() << "SwitchStatus Event Subscription started successfully.";
//     }
//     else
//     {
//         qDebug() << "SwitchStatus Event Subscription failed.";
//     }

// }

void SwitchStaus::eventStatuCallback(const QString &content)
{
    //qDebug()<<"In eventStatuCallback ~~~~~~"<<Qt::endl;
    //QString rawJson = QString::fromStdString(msg.content());  // 原始 JSON 字符串
    QString rawJson = content;
    //std::cout<<"SwitchStatu receive event :"<<msg.content()<<std::endl;
    QString a, b;

    // 解析 JSON
    {
        QMutexLocker locker(&mSwitchStatuMutex);
        QJsonParseError parseError;
        QJsonDocument doc = QJsonDocument::fromJson(rawJson.toUtf8(), &parseError);

        if (parseError.error == QJsonParseError::NoError && doc.isObject()) {
            QJsonObject obj = doc.object();

            // 提取 "event" 字段的键值对
            if (obj.contains("event")) {
                a = "event";  // 键名固定为 "event"
                b = obj["event"].toString();  // 提取值部分

            }
            else if(obj.contains("warning"))
            {
                a = "waring";
                b = obj["warning"].toString();  // 提取值部分

            }
            else if(obj.contains("error"))
            {
                a = "error";
                b = obj["error"].toString();  // 提取值部分
            }
            else if(obj.contains("fatal"))
            {
                a = "fatal";
                b = obj["fatal"].toString();  // 提取值部分
            }
            else if(obj.contains("command"))
            {
                a = "command";
                b = obj["command"].toString();
            }

            //std::cout<<"switch b="<<b.toStdString()<<std::endl;

            exEventMsg[0] = a;
            exEventMsg[1] = b;

        } else {
            qWarning() << "JSON11 解析失败：" << parseError.errorString();
        }
    }
    //emit upSubEvent(exEventMsg);

    if(exEventMsg[1]=="State switched to:root.enable.halt")
    {
        emit colorChanged("yellow"); // 黄色，作为例子
        QMetaObject::invokeMethod(
            this,                       // 目标对象（通常是主窗口）
            "slotHaltUi",                 // 槽函数名
            Qt::QueuedConnection        // 确保在主线程执行
            );

    }
    else if(exEventMsg[1]=="State switched to:root.enable.command")
    {
        emit colorChanged("green");  // 绿色
        QMetaObject::invokeMethod(
            this,                       // 目标对象（通常是主窗口）
            "slotCommandUi",                 // 槽函数名
            Qt::QueuedConnection        // 确保在主线程执行
            );

    }
    else if(exEventMsg[1]=="State switched to:root.ready")
    {
        emit colorChanged("gray");    // 灰色
        QMetaObject::invokeMethod(
            this,                       // 目标对象（通常是主窗口）
            "slotReadyUi",                 // 槽函数名
            Qt::QueuedConnection        // 确保在主线程执行
            );
    }
}


void SwitchStaus::slotHaltUi()
{

    ui->ptn_switch->setText("command");
    ui->ptn_ready->setStyleSheet("background-color: transparent; border: 2px solid gray;outline: none; border-radius: 25px;width: 50px; height: 50px;");
    ui->ptn_halt->setStyleSheet("background-color: yellow; border: 2px solid yellow; border-radius: 25px; width: 48px; height: 48px;");
    ui->ptn_command->setStyleSheet("background-color: transparent; border: 2px solid green; border-radius: 25px;width: 48px; height: 48px;");
    ui->ptn_error->setStyleSheet("background-color: transparent; border: 2px solid red; border-radius: 25px; width: 48px; height: 48px;");
}

void SwitchStaus::slotCommandUi()
{
    ui->ptn_switch->setText("");
    ui->ptn_ready->setStyleSheet("background-color: transparent; border: 2px solid gray;outline: none; border-radius: 25px;width: 50px; height: 50px;");
    ui->ptn_halt->setStyleSheet("background-color: transparent; border: 2px solid yellow; border-radius: 25px; width: 48px; height: 48px;");
    ui->ptn_command->setStyleSheet("background-color: green; border: 2px solid green; border-radius: 25px;width: 48px; height: 48px;");
    ui->ptn_error->setStyleSheet("background-color: transparent; border: 2px solid red; border-radius: 25px; width: 48px; height: 48px;");
}

void SwitchStaus::slotReadyUi()
{
    ui->ptn_switch->setText("halt");

    // 恢复 pt_ready 状态为默认灰色背景
    ui->ptn_ready->setStyleSheet("background-color: gray; border: 2px solid gray; outline: none; border-radius: 25px; width: 50px; height: 50px;");

    // 恢复 pt_halt 状态为透明背景，边框为黄色
    ui->ptn_halt->setStyleSheet("background-color: transparent; border: 2px solid yellow; border-radius: 25px; width: 48px; height: 48px;");

    // 恢复 pt_command 状态为透明背景，边框为绿色
    ui->ptn_command->setStyleSheet("background-color: transparent; border: 2px solid green; border-radius: 25px; width: 48px; height: 48px;");

    // 恢复 pt_error 状态为透明背景，边框为红色
    ui->ptn_error->setStyleSheet("background-color: transparent; border: 2px solid red; border-radius: 25px; width: 48px; height: 48px;");

}

void SwitchStaus::attachToNode(QSharedPointer<DeviceNode> node)
{
    if (m_node) {
        disconnect(m_node.data(), &DeviceNode::cmdReceived,
                   this, &SwitchStaus::onDataReceived);
        disconnect(m_node.data(), &DeviceNode::eventReceived,
                   this, &SwitchStaus::onEventReceived);
    }
    m_node = node;
    if (m_node) {
        connect(m_node.data(), &DeviceNode::cmdReceived,
                this, &SwitchStaus::onDataReceived);
        connect(m_node.data(), &DeviceNode::eventReceived,
                this, &SwitchStaus::onEventReceived);
    }
}

void SwitchStaus::onDataReceived(const QString& content)
{

    //qDebug()<<"SwitchStaus Received Statu "<<content<<Qt::endl;
    if(flagInitCount<3)
    {
        parseSensorData(content);

    }
    if(flagInitCount>80)
        flagInitCount = 0;
    flagInitCount++;
}

void SwitchStaus::onEventReceived(const QString& content)
{
    eventStatuCallback(content);
    //qDebug()<<"SwitchStaus Received Event "<<content<<Qt::endl;
}

void SwitchStaus::pubMsg(const QString &content)
{
    if(m_node)
    {
        //QString content = "pub test";
        QString id = QString::fromStdString(mDeviceName);
        //QString id = "ORS_Cask";
        m_node->publishCmd(id,content);
    }
}

void SwitchStaus::initSwitch()
{
        QString pubcontent = "switchState(s=Ready)";
        pubMsg(pubcontent);
        qDebug()<<"initSwitch go successful"<<Qt::endl;
}


void SwitchStaus::parseSensorData(const QString &content)
{
    // 1. QString 转 QByteArray
    QByteArray jsonData = content.toUtf8();
    // 2. 解析
    QJsonParseError err;
    QJsonDocument doc = QJsonDocument::fromJson(jsonData, &err);
    if (err.error != QJsonParseError::NoError) {
        qWarning() << "JSON parse error:" << err.errorString();
        return ;
    }
    if (!doc.isObject()) {
        qWarning() << "JSON is not an object";
        return ;
    }
    // 3. 拆字段
    QJsonObject obj = doc.object();
    if (!obj.contains("fsmState"))
    {
        qWarning() << "Missing expected fields in JSON";
        return ;
    }
    QString deviceStatus = obj.value("fsmState").toString();
    //qDebug()<<"SwitchStatu , deviceStatus = "<<deviceStatus<<Qt::endl;
    if(deviceStatus == "root.enable.halt")
    {
        emit colorChanged("yellow"); // 黄色，作为例子
        QMetaObject::invokeMethod(
            this,                       // 目标对象（通常是主窗口）
            "slotHaltUi",                 // 槽函数名
            Qt::QueuedConnection        // 确保在主线程执行
            );
    }
    else if(deviceStatus=="root.enable.command")
    {
        emit colorChanged("green");  // 绿色
        QMetaObject::invokeMethod(
            this,                       // 目标对象（通常是主窗口）
            "slotCommandUi",                 // 槽函数名
            Qt::QueuedConnection        // 确保在主线程执行
            );

    }
    else if(deviceStatus=="root.ready")
    {
        emit colorChanged("gray");    // 灰色
        QMetaObject::invokeMethod(
            this,                       // 目标对象（通常是主窗口）
            "slotReadyUi",                 // 槽函数名
            Qt::QueuedConnection        // 确保在主线程执行
            );

    }


    //return true;
}

// 拖动窗口相关
void SwitchStaus::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton && ui->titleBarWidget->geometry().contains(event->pos())) {
        m_mousePressed = true;
        m_dragPos = event->globalPosition().toPoint() - frameGeometry().topLeft();
    }
}

void SwitchStaus::mouseMoveEvent(QMouseEvent *event)
{
    if (m_mousePressed && (event->buttons() & Qt::LeftButton)) {
        move(event->globalPosition().toPoint() - m_dragPos);
    }
}

void SwitchStaus::mouseReleaseEvent(QMouseEvent *)
{
    m_mousePressed = false;
}
